<?php

namespace app\admin\controller\shopro;

use addons\withdraw\model\Withdraw;
use app\admin\model\shopro\user\Oauth;
use app\admin\model\shopro\user\User;
use app\common\controller\Backend;
use app\common\library\Weixin;
use think\Db;
use think\Exception;

/**
 * 用户提现
 *
 * @icon fa fa-circle-o
 */
class UserWalletApply extends Backend
{

    /**
     * UserWalletApply模型对象
     * @var \app\admin\model\shopro\UserWalletApply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\UserWalletApply;
        $this->view->assign("getTypeList", $this->model->getGetTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function applyOper($id)
    {
        $status = $this->request->post('status', -1);
        $status_msg = $this->request->post('status_msg', '');

        $apply = $this->model->get($id);

        if ($apply->status != 0) {
            $this->error('该提现申请已处理，不能重复处理');
        }

        $third_platform = Oauth::where(['platform'=>'wxMiniProgram','user_id' => $apply['user_id']])->find();
        if(empty($third_platform['openid'])){
            $this->error('非微信小程序授权用户,不可微信提现');
        }

        try {
            $apply = Db::transaction(function () use ($apply, $status, $status_msg, $third_platform) {
                $apply->status = $status;
                $apply->status_msg = $status_msg;
                $apply->save();

                if ($status == -1) {
                    // 把提现的金额重新加回去
                    $total_money = $apply->money + $apply->charge_money;
                    $bank_info = json_decode($apply, true);
                    $ext = array_merge([
                        'money' => $apply->money,
                        'charge' => $apply->charge_money
                    ], $bank_info);

                    \addons\shopro\model\User::moneyAdd($apply->user_id, $total_money, 'cash_error', $apply->id, $ext);
                } else {
                    /////////////////////////付款/////////////////////////////
                    $paretner_pay_no = date('YmdHis').rand(1000, 9999);//商户订单号
                    $weixin = new Weixin();
                    $res = $weixin->sendMoney($apply->money, $third_platform['openid'],$paretner_pay_no, $apply->client_ip, '用户提现');
                    if (isset($res['return_code']) && $res['return_code'] == "SUCCESS"
                        && isset($res['result_code']) && $res['result_code'] == "SUCCESS") {
                        //TODO 支付成功,记录withdraw表
                        $withdrawData = [
                            'user_id'   => $apply->user_id,
                            'money'     => $apply->money,
                            'handingfee'=> $apply->charge_money,
                            'taxes'     => 0,
                            'type'      => 'weixin',
                            'account'   => $third_platform['openid'],
                            'memo'      => '用户提现:' . json_encode($res,true),
                            'orderid'   => $paretner_pay_no,
                            'transactionid' => $res['payment_no'],
                            'status'    => 'successed',
                            'transfertime' => time(),
                            'createtime'=> time(),
                        ];
                        Withdraw::create($withdrawData);

                    } else {
                        //记录日志
                        throw Exception($res['return_msg'].":".$res['err_code_des']);
                    }
                }

                // 提现结果通知
                $user = \addons\shopro\model\User::where('id', $apply['user_id'])->find();
                $user->notify(
                    new \addons\shopro\notifications\Wallet([
                        'apply' => $apply,
                        'event' => 'wallet_apply'
                    ])
                );

                return $apply;
            });
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }

        return $this->success('操作成功', null, $apply);
    }


}
